//
//  AllCommentViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/8/5.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "AllCommentViewController.h"

#import "AllCommentTableViewCell.h"
#import "ReplyTableViewCell.h"
#import "UIImage+GradientColor.h"

@interface AllCommentViewController ()<UITableViewDelegate, UITableViewDataSource, UITextViewDelegate>

@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@property (nonatomic, strong) UIView *commentView;
@property (nonatomic, strong) NSString *appraiseId;

@end

@implementation AllCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"评论列表";
    
    self.dataArray = [NSMutableArray array];
    self.currentPage = 1;
    self.appraiseId = @"";
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49))];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 12; i++) {
        NSString *imageName = [NSString stringWithFormat:@"%d",i];
        [arr addObject:ImageWithName(imageName)];
    }
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [header setImages:arr forState:MJRefreshStateRefreshing];
    self.tableView.mj_header = header;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.tableView.mj_header beginRefreshing];
    
    UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#ff1162"),REXADECIMALCOLOR(@"#fe4e4e")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(SCREEN_WIDTH, ScreenX375(49))];
    UIButton *commentBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49), SCREEN_WIDTH, ScreenX375(49))];
    [commentBtn setTitle:@"点我发表你的意见" forState:UIControlStateNormal];
    [commentBtn setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateNormal];
    commentBtn.titleLabel.font = Kfont(16);
    [commentBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
    commentBtn.backgroundColor = REXADECIMALCOLOR(@"#ffd100");
    [commentBtn addTarget:self action:@selector(commentAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:commentBtn];
}

- (void)commentAction {
    self.appraiseId = @"";
    [self showComment];
}

- (void)headerRefresh {
    _currentPage = 1;
    [self getData];
    self.tableView.mj_footer.hidden = NO;
}

- (void)footerRefresh {
    if (_currentPage <= _totalPage) {
        
        _currentPage++;
        [self getData];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
    }else{
        
//        [HttpManager showNoteMsg:@"已经到底啦"];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.hidden = YES;
    }
}

- (void)getData {
    NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"proId":_proId,@"pageSize":@"10",@"page":[NSNumber numberWithInteger:_currentPage]}];
    [HttpManager postHttpRequestByGet:[NSString stringWithFormat:@"%@api/getProAppraise",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            if (self.currentPage == 1) {
                [self.dataArray removeAllObjects];
            }
            self.totalPage = [successResponse[@"data"][@"pages"] integerValue];
            NSError *error = nil;
            for (NSDictionary *dic in successResponse[@"data"][@"appraises"]) {
                CommentModel *model = [[CommentModel alloc] initWithDictionary:dic error:&error];
                [self.dataArray addObject:model];
            }
            if (self.totalPage == self.currentPage) {
                self.tableView.mj_footer.hidden = YES;
            }
            if ([successResponse[@"data"][@"appraises"] count] == 0) {
                [HttpManager showNoteMsg:@"暂无更多数据"];
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }else if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    CommentModel *model = _dataArray[section];
    return model.list.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentModel *model = _dataArray[indexPath.section];
    if (indexPath.row == 0) {
        AllCommentTableViewCell *cell = [AllCommentTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.commentModel = model;
        cell.appraiseClick = ^{
            [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/zan",REQUESTHEADER] andParameter:@{@"proId":model.Id,@"userId":kNSUDefaultReadKey(@"userId"),@"type":@"1"} success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                if ([status isEqualToString:@"200"]) {
                    if ([model.isZan integerValue]) {
                        model.isZan = @"0";
                        model.zanNum = [NSString stringWithFormat:@"%ld",[model.zanNum integerValue] - 1];
                    }else {
                        model.isZan = @"1";
                        model.zanNum = [NSString stringWithFormat:@"%ld",[model.zanNum integerValue] + 1];
                    }
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }else {
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [HttpManager showFail];
            }];
        };
        cell.commentClick = ^{
            self.appraiseId = model.Id;
            [self showComment];
        };
        return cell;
    }else {
        ReplyTableViewCell *cell = [ReplyTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
        NSDictionary *dic = model.list[indexPath.row - 1];
        NSError *error;
        CommentModel *replyModel = [[CommentModel alloc] initWithDictionary:dic error:&error];
        cell.commentModel = replyModel;
        
        if (indexPath.row == 1 && indexPath.row == model.list.count) {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bgView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft | UIRectCornerBottomRight | UIRectCornerTopRight cornerRadii:CGSizeMake(8,8)];
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = cell.bgView.bounds;
            maskLayer.path = maskPath.CGPath;
            cell.bgView.layer.mask = maskLayer;
        }else if (indexPath.row == 1 && indexPath.row != model.list.count) {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(8,8)];
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = cell.bgView.bounds;
            maskLayer.path = maskPath.CGPath;
            cell.bgView.layer.mask = maskLayer;
        }else if (indexPath.row == model.list.count && indexPath.row != 1) {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bgView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(8,8)];
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = cell.bgView.bounds;
            maskLayer.path = maskPath.CGPath;
            cell.bgView.layer.mask = maskLayer;
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentModel *model = _dataArray[indexPath.section];
    self.appraiseId = model.Id;
    [self showComment];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentModel *model = _dataArray[indexPath.section];
    if (indexPath.row == 0) {
        return ScreenX375(57) + kGetStringHeight(model.content, CGSizeMake(SCREEN_WIDTH - ScreenX375(64), MAXFLOAT), Kfont(14));
    }
    NSDictionary *dic = model.list[indexPath.row - 1];
    NSError *error;
    CommentModel *replyModel = [[CommentModel alloc] initWithDictionary:dic error:&error];
    return ScreenX375(62) + kGetStringHeight(replyModel.content, CGSizeMake(SCREEN_WIDTH - ScreenX375(128), MAXFLOAT), Kfont(12));
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return ScreenX375(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

- (void)close {
    [_commentView removeFromSuperview];
}

- (void)showComment {
    if (!_commentView) {
        _commentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _commentView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
        
        UIView *commentBg = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(24), ScreenX375(210), SCREEN_WIDTH - ScreenX375(48), ScreenX375(194))];
        commentBg.backgroundColor = REXADECIMALCOLOR(@"#f5f5f5");
        commentBg.layer.cornerRadius = ScreenX375(8);
        commentBg.clipsToBounds = YES;
        [_commentView addSubview:commentBg];
        
        UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(29), ScreenX375(29))];
        [closeBtn setImage:ImageWithName(@"关闭") forState:UIControlStateNormal];
        [closeBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
        [commentBg addSubview:closeBtn];
        
        UITextView *commentText = [[UITextView alloc] initWithFrame:CGRectMake(ScreenX375(25), ScreenX375(23), SCREEN_WIDTH - ScreenX375(98), ScreenX375(105))];
        commentText.backgroundColor = [UIColor whiteColor];
        commentText.font = Kfont(14);
        commentText.layer.cornerRadius = ScreenX375(4);
        commentText.clipsToBounds = YES;
        commentText.text = @"写评论...";
        commentText.tag = 555;
        commentText.textColor = REXADECIMALCOLOR(@"#999999");
        commentText.delegate = self;
        [commentBg addSubview:commentText];
        
        UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#ff1162"),REXADECIMALCOLOR(@"#fe4e4e")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(ScreenX375(103), ScreenX375(112))];
        UIButton *commitBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(112), ScreenX375(144), ScreenX375(103), ScreenX375(30))];
        [commitBtn setTitle:@"提交评论" forState:UIControlStateNormal];
        [commitBtn setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateNormal];
        commitBtn.titleLabel.font = Kfont(15);
        [commitBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
        commitBtn.layer.cornerRadius = ScreenX375(15);
        commitBtn.layer.masksToBounds = YES;
        [commitBtn addTarget:self action:@selector(commitComment) forControlEvents:UIControlEventTouchUpInside];
        [commentBg addSubview:commitBtn];
    }
    [kKeyWindow addSubview:_commentView];
}

- (void)commitComment {
    UITextView *textView = [_commentView viewWithTag:555];
    if (textView.text.length == 0) {
        [HttpManager showNoteMsg:@"请输入评论内容"];
        return;
    }
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/appraisePro",REQUESTHEADER] andParameter:@{@"proId":_proId,@"content":textView.text,@"userId":kNSUDefaultReadKey(@"userId"),@"parentId":self.appraiseId} success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            [HttpManager showNoteMsg:@"评论成功"];
            [self close];
            [self.tableView.mj_header beginRefreshing];
            self.appraiseId = @"";
            textView.textColor = REXADECIMALCOLOR(@"#999999");
            textView.text = @"写评论...";
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

-(void)textViewDidBeginEditing:(UITextView *)textView{
    if (textView.tag == 555) {
        if ([textView.text isEqualToString:@"写评论..."]) {
            textView.textColor = [UIColor blackColor];
            textView.text = @"";
        }
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.tag == 500) {
        if (textView.text.length < 1) {
            textView.textColor = REXADECIMALCOLOR(@"#999999");
            textView.text = @"写评论...";
        }
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
